<?php
namespace app\user\model\login;
use app\common\model\Base;
use app\user\model\Auth as auth;
use app\user\model\User as user;
use app\publictool\controller\PublicTool;
use think\Validate;
class PhoneLogin extends Base{
    protected $table = 'gym_user_info';

    //用户登录
    public static function signIn(){
        $data = self::getInputData();
        $allowFields = ['hash_value','last_login_time'];
        $validate = new Validate(
            [
                'phone_num'=>'require',
                'password'=>'require'
            ],
            [
                'phone_num.require'=>'请填写手机号码！',
                'password.require'=>'请填写密码！',
            ]
        );
        $verify = $validate->check($data);
        if(!$verify){
            echo $validate->getError();
            exit;
        }
        $queryCondition['phone_num'] = $data['phone_num'];
        $relObj = static::where($queryCondition);
        if(!$relObj->count()){
            abort(-0020,'用户不存在！');
            exit;
        }
        $result = $relObj->where(['phone_num'=>$data['phone_num']])->find();
        if(strcmp(PublicTool::passwordEncryption($data['password']),$result->getAttr('password')) !== 0){
            abort(-0021,'密码不正确！');
        }
        //用户登录成功,更新用户的hash值的状态
        $hashValue = self::generateUniqueSignForUser($result->getAttr('uuid'));
        $dataObject = new self();
        $success = $dataObject->allowField($allowFields)->save(
        [
            'hash_value'=>$hashValue,//当前用户的在线值
            'last_login_time'=>time()//当前用户的下线值
        ]
        ,['uuid'=>$result->getAttr('uuid')]);
        if(!$success){
            abort(-0023,'登录失败请重试！');
        }
        $userInfo = user::getUserManagerInfo($result->getAttr('uuid'));
        $response = ['hash_value'=>$hashValue];
        $response = array_merge($response,$userInfo);
        return $response;
    }

     /**
    *给用户创建唯一的登录签名，代替用户的账户名和密码,进行操作
    *@param $uuid 当前用户的uuid 必须是已经注册过的用户才可以
    */
    public static function generateUniqueSignForUser($uuid){

        $microTime = microtime(); //毫秒
        list($a_dec,$a_sec) = explode(' ',$microTime);
        $dec_hex = dechex($a_dec*10000000);
        $asc_hex = dechex($a_sec);
        $sign='';
        $sign.=$dec_hex;
        $sign.=$uuid;
        $sign.=$asc_hex;
        return sha1($sign);
    }


    //假的删除用户信息
    public static function undata($data=null){
        $data['status'] = 0;
        $data['uuid'] = $data['uuid'];
        $user = Loader::model('\\app\\user\\model\\User');
        $user::monity($data);
    }

}
